package com.io.util;

import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * properties解析工具
 * 
 * @author yangyx
 * @date 2014/09/04
 */
public class PropertiesUtil {

	/*-------------------------------------------
    |             C O N S T A N T S             |
    ============================================*/
	/** Log */
	private static final Log log = LogFactory.getLog(PropertiesUtil.class);
	
	/*-------------------------------------------
    |    I N S T A N C E   V A R I A B L E S    |
    ============================================*/
	/** 定义Properties */
	private Properties props;

	/*-------------------------------------------
    |               M E T H O D S               |
    ============================================*/
	/**
	 * 构造函数
	 * 
	 * @param fileName
	 */
	public PropertiesUtil(String fileName) {
		readProperties(fileName);
	}

	/**
	 * 读取properties文件
	 * 
	 * @param fileName
	 */
	private void readProperties(String fileName) {
		try {
			// 初始化properties
			props = new Properties();
			
			// 根据反射找到对应的properties文件路径
			InputStream fis = getClass().getResourceAsStream(fileName);
			
			// 加载该properties文件
			props.load(fis);
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error("加载properties文件失败!");
		}
	}

	/**
	 * 根据key获取属性值
	 */
	public String getProperty(String key) {
		return props.getProperty(key);
	}

	/**
	 * 获取所有属性，返回一个map,不常用 可以试试props.putAll(t)
	 */
	@SuppressWarnings("rawtypes")
	public Map<String, Object> getAllProperty() {
		Map<String, Object> map = new HashMap<String, Object>();
		Enumeration enu = props.propertyNames();
		while (enu.hasMoreElements()) {
			String key = (String) enu.nextElement();
			String value = props.getProperty(key);
			map.put(key, value);
		}
		return map;
	}

	public static void main(String[] args) {
		PropertiesUtil util = new PropertiesUtil("/ftp.config.properties");
		String propertyValue = util.getProperty("ftp.server.url");
		System.out.println(propertyValue);
	}
}
